﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using AxAcroPDFLib;

using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;
using ESOL.Business.Bpt;
using ESOL.WinUI.Sales;
using ESOL.Business.Sec;
using ESOL.Common.Entity;
using ESOL.Common;
using ESOL.Business.Sales;
using ESOL.Business.Mst;
using ESOL.WinUI.Hr;
using ESOL.Common.Schema;

namespace ESOL.WinUI.Bpt
{
    public partial class frmMaintainProjectApplication : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public BptApplicationEntity SelectedBptApplication { get; set; }
        private List<BptApplicationItemEntity> DeleteList = new List<BptApplicationItemEntity>();
        #endregion

        #region Constructor
        public frmMaintainProjectApplication()
        {
            InitializeComponent();
            if (SelectedBptApplication == null)
            {
                SelectedBptApplication = new BptApplicationEntity();
                SelectedBptApplication.ApplicationId = Guid.NewGuid().ToString();
            }
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "DRAW", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbApplicationType, "DT", false);
        }

        private void BindDataGridDetail()
        {
            if (SelectedBptApplication == null)
            {
                gvDetail.DataSource = null;
                return;
            }
            DataTable dt = BptApplicationItemBs.GetApplicationItemByID(SelectedBptApplication.ApplicationId);
            if (dt == null)
            {
                gvDetail.DataSource = null;
                return;
            }
            dt.AcceptChanges();
            gvDetail.DataSource = dt;
            DeleteList = new List<BptApplicationItemEntity>();

        }

        private void BindFilesGridView()
        {
            if (SelectedBptApplication == null)
            {
                gvFileList.DataSource = null;
                return;
            }
            DataTable dt = BptApplicationAttachedBs.GetFilesAppByID(SelectedBptApplication.ApplicationId);
            if (dt == null)
            {
                gvFileList.DataSource = null;
                return;
            }
            dt.AcceptChanges();
            gvFileList.DataSource = dt;
        }

        private void SetFields()
        {
            BindDataGridDetail();
            if (SelectedBptApplication == null)
            {
                return;
            }
            if (ThisActionType == ActionType.New)
            {
                txtBrtApplicationCode.Text = "自动生成";
            }
            else
            {
                txtBrtApplicationCode.Text = SelectedBptApplication.ApplicationCode;//制图计划单号
            }
            if (string.IsNullOrEmpty(SelectedBptApplication.ProdApplicationId) == false)//生产计划申请单号
            {
                SalesProdPlanApplicationEntity ProdPlanApplication = SalesProdPlanApplicationBs.GetSalesProdPlanApplicationByID(SelectedBptApplication.ProdApplicationId);
                if (ProdPlanApplication != null)
                {
                    txtProApplicationcode.Text = ProdPlanApplication.ApplicationCode;
                    txtProApplicationcode.Tag = ProdPlanApplication;
                }
            }
            if (string.IsNullOrEmpty(SelectedBptApplication.ApplicationPerson) == false)//申请人
            {
                MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedBptApplication.ApplicationPerson);
                if (person != null)
                {
                    txtApplicationperson.Tag = person;
                    txtApplicationperson.Text = person.NameCn + " (" + person.PersonCode + ")";
                }
            }
            cmbApplicationType.SetSelectedValue(SelectedBptApplication.ApplicationType);
            cmbStatus.SetSelectedValue(SelectedBptApplication.Status);//状态
            txtRemark.Text = SelectedBptApplication.Remark;//备注
        }

        private void SetEntity()
        {
            if (txtProApplicationcode.Tag != null && txtProApplicationcode.Tag.GetType() == typeof(SalesProdPlanApplicationEntity))
            {
                SelectedBptApplication.ProdApplicationId = ((SalesProdPlanApplicationEntity)txtProApplicationcode.Tag).ApplicationId;
            }
            SelectedBptApplication.ApplicationCode = txtBrtApplicationCode.Text;
            SelectedBptApplication.Remark = txtRemark.Text;
            SelectedBptApplication.ApplicationType = cmbApplicationType.SelectedValue.ToString();
            if (!txtAppointApprovePerson1.Text.Equals(""))
            {
                SelectedBptApplication.ApprovedBy = ((MstPersonEntity)txtAppointApprovePerson1.Tag).PersonId;
            }
            if (ThisActionType == ActionType.New)
            {
                SelectedBptApplication.Status = "DRAW01";
                SelectedBptApplication.ApplicationPerson = CommonParameter.CurrentUser.PersonId;
                SelectedBptApplication.CreatedDate = DateTime.Now;
                SelectedBptApplication.CreatedBy = CommonParameter.CurrentUser.PersonId;
                SelectedBptApplication.LastModifiedDate = DateTime.Now;
                SelectedBptApplication.LastModifiedBy = CommonParameter.CurrentUser.PersonId;

            }
            if (ThisActionType == ActionType.Modify)
            {
                SelectedBptApplication.Status = "DRAW01";
                SelectedBptApplication.LastModifiedDate = DateTime.Now;
                SelectedBptApplication.LastModifiedBy = CommonParameter.CurrentUser.PersonId;

            }
            if (ThisActionType == ActionType.Approve)
            {
                SelectedBptApplication.ApprovedDate = DateTime.Now;
                SelectedBptApplication.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                SelectedBptApplication.LastModifiedDate = DateTime.Now;
                SelectedBptApplication.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }

        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtRemark.Text))
            {
                MessageBox.Show("任务说明不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (gvDetail.DataSource == null)
            {
                MessageBox.Show("任务列表不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtAppointApprovePerson1.Text))
            {
                MessageBox.Show("指定审核人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvDetail.DataSource as DataTable;
            int i = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty(dr["DELIVERY_DATE"].ToString()))
                {
                    MessageBox.Show("明细表第" + i.ToString() + "交图日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
                i++;
            }
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    bool isSuccessful = BptApplicationBs.SaveBptApplication(true, SelectedBptApplication, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    bool isSuccessful = BptApplicationBs.SaveBptApplication(false, SelectedBptApplication, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SelectedBptApplication.ApprovedDate = DateTime.Now;
                    SelectedBptApplication.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    bool isSuccessful = BptApplicationBs.ApprovBuleprintapplication(SelectedBptApplication);
                    //bool isSuccessful = BptApplicationBs.UpdateBptApplication(SelectedBptApplication);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void SendMessage(string sMessageTitle, string sSender, string sMessageBody, string MessageLevel)
        {
            MstMessageEntity message = new MstMessageEntity();
            message.MessageId = Guid.NewGuid().ToString();
            message.MessateTitle = sMessageTitle;
            message.MessageSender = sSender;
            message.MessageBody = sMessageBody;
            message.MessageLevel = MessageLevel;
            message.FormName = "ESOL.WinUI.Bpt.frmDrawBlueprintManage";
            message.MessageDate = DateTime.Now;
            //List<MstPersonEntity> toList = SecUserBs.GetPersonIdByFormAndObject("ESOL.WinUI.Bpt.frmDrawBlueprintManage", "分配任务", "btnModify");
            List<MstPersonEntity> toList = MstMessageBs.GetPersonIdByFormAndObject("ESOL.WinUI.Bpt.frmDrawBlueprintManage", "btnModify", sSender);
            MstMessageBs.SendMessage(message, toList);
        }

        private byte[] FileToByte(string pStrFName)
        {
            FileInfo fi = new FileInfo(pStrFName);
            FileStream fs = fi.OpenRead();
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
            return bytes;
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            BindComboBox();
            SetFields();
            BindFilesGridView();
            try
            {
                Directory.Delete("C:" + @"\" + "TempPictures", true);
            }
            catch
            { }
            Directory.CreateDirectory("C:" + @"\" + "TempPictures");
            base.OnShown(e);
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedBptApplication = new BptApplicationEntity();
                SelectedBptApplication.ApplicationId = Guid.NewGuid().ToString();
                SetFields();
            }
        }

        protected override void Click_Approve()
        {
            if (SelectedBptApplication == null)
            {
                return;
            }
            SelectedBptApplication.Status = "DRAW02";
            if (Save())
            {
                SendMessage("新制图任务", CommonParameter.CurrentUser.PersonId, "有新的制图任务需要分配了；", MessageLevel.ML03.ToString());
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_Reject()
        {
            if (SelectedBptApplication == null)
            {
                return;
            }
            SelectedBptApplication.Status = "DRAW03";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void cmbApplicationType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbApplicationType.SelectedValue == null)
            {
                return;
            }
            if (cmbApplicationType.SelectedValue.ToString().Equals("DT02"))
            {
                gridView2.Columns[5].Caption = "要求交图日期";
                gridView2.Columns[6].Visible = false;
            }
            else
            {
                gridView2.Columns[5].Caption = "交货日期";
                gridView2.Columns[6].Visible = true;
            }
        }

        private void txtProApplicationcode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductPlanApplicationQuery frm = new frmMaintainProductPlanApplicationQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProdPlanApplication != null)
            {
                txtProApplicationcode.Text = frm.SelectedProdPlanApplication.ApplicationCode;
                txtProApplicationcode.Tag = frm.SelectedProdPlanApplication;
            }
            else
            {
                txtProApplicationcode.Text = "";
                txtProApplicationcode.Tag = null;
            }
        }

        private void txtAppointApprovePerson1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtAppointApprovePerson1.Text = frm.SelectedPerson.NameCn;
                txtAppointApprovePerson1.Tag = frm.SelectedPerson;
            }
            else
            {
                txtAppointApprovePerson1.Text = "";
                txtAppointApprovePerson1.Tag = null;
            }
        }

        DataRow drAttachSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drAttachSelected = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        DataRow drItemSelected;
        private void gridView2_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drItemSelected = gridView2.GetDataRow(e.FocusedRowHandle);
        }

        private void tsmNewAttach_Click(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.New)
            {
                MessageBox.Show("请先保存申请单后再上传附件！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (ThisActionType != ActionType.Modify)
            {
                MessageBox.Show("非修改模式下，不允许上传附件！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (gvFileList.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvFileList.DataSource;
            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);
        }

        private void tsmDeleteAttach_Click(object sender, EventArgs e)
        {
            if (drAttachSelected == null)
            {
                return;
            }
            if (ThisActionType != ActionType.Modify)
            {
                MessageBox.Show("非修改模式下，不允许删除附件！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            BptApplicationAttachedEntity Attentity = new BptApplicationAttachedEntity(drAttachSelected);
            bool result = BptApplicationAttachedBs.DeleteBptApplicationAttached(Attentity);
            if (result)
            {
                MessageBox.Show("删除成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("删除失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (drAttachSelected == null)
            {
                return;
            }
            if (ThisActionType != ActionType.Modify)
            {
                MessageBox.Show("非修改模式下，不允许上传附件！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            OpenFileDialog op = new OpenFileDialog();
            op.Title = "图片文件选择";
            op.FileName = "";
            op.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
            op.Filter = "图片文件(*.jpg,*.pdf)|*.jpg;*.pdf";
            op.ValidateNames = true;
            op.CheckFileExists = true;
            op.CheckPathExists = true;
            if (op.ShowDialog() == DialogResult.OK)
            {
                drAttachSelected["FILE_NAME"] = op.FileName;
            }
        }

        private void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (drAttachSelected == null)
            {
                return;
            }
            BptApplicationAttachedEntity Attentity = new BptApplicationAttachedEntity(drAttachSelected);
            EsolWevServices.EsolService EService = new EsolWevServices.EsolService();
            if (string.IsNullOrEmpty(Attentity.AttachedId))
            {
                MessageBox.Show("请先保存附件后再下载！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            try
            {
                string sFileName = Attentity.AttachedId + Attentity.FileName.Substring(Attentity.FileName.Length - 4);
                byte[] bytes = EService.DownLodeBptappfiles(sFileName);
                if (bytes != null)
                {
                    if (sFileName.Substring(sFileName.Length - 3).ToUpper().Equals("JPG"))
                    {
                        Image img = CommonFunctions.byteArrayToImage(bytes);
                        CommonFunctions.OpenPicViewer(img);
                    }
                    if (sFileName.Substring(sFileName.Length - 3).ToUpper().Equals("PDF"))
                    {
                        string ssrt = "C:" + @"\" + "TempPictures" + @"\" + sFileName;
                        FileStream fs;
                        if (System.IO.File.Exists(ssrt))
                        {
                            fs = new FileStream(ssrt, FileMode.Truncate);
                        }
                        else
                        {
                            fs = new FileStream(ssrt, FileMode.CreateNew);
                        }
                        BinaryWriter br = new BinaryWriter(fs);
                        br.Write(bytes, 0, bytes.Length);
                        br.Close();
                        fs.Close();
                        System.Diagnostics.Process.Start(ssrt);
                    }
                }
                else
                {
                    MessageBox.Show("找不到对应图片！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请先选择一行记录！");
            }
        }

        private void repositoryItemButtonEdit3_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (drAttachSelected == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(drAttachSelected["FILE_NAME"].ToString()))
            {
                MessageBox.Show("请先选择需要上传的附件后再保存！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (!System.IO.File.Exists(drAttachSelected["FILE_NAME"].ToString()))
            {
                MessageBox.Show("文件不存在，请重新选择！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            DialogResult dlresult = MessageBox.Show("是否上传并保存附件！", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dlresult == DialogResult.OK)
            {
                string sRemarks = "";
                if (string.IsNullOrEmpty(drAttachSelected["REMARK"].ToString()) == false)
                {
                    sRemarks = drAttachSelected["REMARK"].ToString();
                }
                BptApplicationAttachedEntity Attentity;
                if (drAttachSelected.RowState != DataRowState.Added)
                {
                    Attentity = new BptApplicationAttachedEntity(drAttachSelected);
                }
                else
                {
                    Attentity = new BptApplicationAttachedEntity();
                    Attentity.AttachedId = Guid.NewGuid().ToString();
                    Attentity.BptApplicationId = SelectedBptApplication.ApplicationId;
                    Attentity.Remark = sRemarks;
                    Attentity.FileName = drAttachSelected["FILE_NAME"].ToString();
                    Attentity.FileType = "申请附件";//申请时上传的文件用0标示，提交任务时上传的文件用1标示
                    Attentity.UploadBy = Common.CommonParameter.CurrentUser.PersonId;
                    Attentity.UploadDate = DateTime.Now;
                }
                if (Attentity.FileType != "申请附件")
                {
                    MessageBox.Show("不能修改提交人上传的文件，请重新选择！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                bool result = BptApplicationBs.SaveBptAppfiles(Attentity, drAttachSelected.RowState.ToString());
                if (result)
                {
                    //上传附件
                    EsolWevServices.EsolService EService = new EsolWevServices.EsolService();
                    byte[] b = CommonFunctions.FileToByte(Attentity.FileName);
                    bool sResult = EService.UpLodeBptappfiles(b, Attentity.AttachedId + Attentity.FileName.Substring(Attentity.FileName.Length - 4));
                    if (sResult)
                    {
                        MessageBox.Show("保存成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("保存失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
                else
                {
                    MessageBox.Show("保存失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void tsmNewItem_Click(object sender, EventArgs e)
        {
            if (gvDetail.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvDetail.DataSource;
            DataRow dr = dt.NewRow();
            dr["APPLICATION_ITEM_ID"] = Guid.NewGuid().ToString();
            dr["APPLICATION_ID"] = SelectedBptApplication.ApplicationId;
            dt.Rows.Add(dr);
        }

        private void tsmDeleteItem_Click(object sender, EventArgs e)
        {
            if (gvDetail.DataSource == null)
            {
                return;
            }
            if (drItemSelected == null)
            {
                return;
            }
            if (drItemSelected.RowState != DataRowState.Added)
            {
                BptApplicationItemEntity entity = new BptApplicationItemEntity(drItemSelected);
                DeleteList.Add(entity);
            }
            DataTable dt = gvDetail.DataSource as DataTable;
            dt.Rows.Remove(drItemSelected);
        }
        #endregion

        private void repositoryItemButtonEdit4_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

        }

        
    }
}
